package com.ray.ba.code.generator.api.controller.v1;

import cn.hutool.core.io.IoUtil;
import cn.hutool.db.Entity;
import com.ray.ba.code.generator.api.dto.DbConnectionProperty;
import com.ray.ba.code.generator.api.dto.GenRequestDto;
import com.ray.ba.code.generator.api.dto.TableRequestDto;
import com.ray.ba.code.generator.app.service.CodeGeneratorService;
import com.ray.ba.starter.code.generator.entity.GenConfig;
import com.ray.ba.starter.web.api.ResponseData;
import com.ray.ba.starter.web.api.ResponsePage;
import com.zaxxer.hikari.HikariDataSource;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

/**
 * CodeGenController
 *
 * @author ray
 * @date 2020/5/7
 */
@RestController
@AllArgsConstructor
@RequestMapping("/v1/generator")
public class CodeGeneratorController {

    CodeGeneratorService codeGeneratorService;

    @PostMapping("/tables")
    public ResponseData listTables(@RequestBody TableRequestDto tableRequestDto) {
        HikariDataSource dataSource = tableRequestDto.getDbConnectionProperty().buildDataSource();
        String tableName = tableRequestDto.getTableName();
        Integer pageNum = tableRequestDto.getPageNum();
        Integer pageSize = tableRequestDto.getPageSize();
        ResponsePage<Entity> entityResponsePage = codeGeneratorService.queryTableByTableNameLike(dataSource, tableName, pageNum, pageSize);
        dataSource.close();
        return ResponseData.success(entityResponsePage);
    }

    @SneakyThrows
    @PostMapping("")
    public void generatorCode(@RequestBody GenRequestDto genRequestDto, HttpServletResponse response) {
        HikariDataSource dataSource = genRequestDto.getDbConnectionProperty().buildDataSource();
        byte[] data = codeGeneratorService.generatorCode(dataSource, genRequestDto.getGenConfig());
        dataSource.close();
        response.reset();
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, String.format("attachment; filename=%s.zip", genRequestDto.getGenConfig().getTableName()));
        response.addHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(data.length));
        response.setContentType("application/octet-stream; charset=UTF-8");

        IoUtil.write(response.getOutputStream(), Boolean.TRUE, data);
    }


}
